<template>
  <div v-if="images && images.length > 0" class="comment-image-viewer">
    <!-- 单张图片 -->
    <div v-if="images.length === 1" class="single-image">
      <div
        class="image-item single"
        @click.prevent.stop="openPreview(0, $event)"
      >
        <img
          :src="debugFormatImageUrl(images[0].fileUrl)"
          :alt="images[0].originalName"
          :style="getImageStyle(images[0])"
          @load="handleImageLoad"
          @error="handleImageError"
        />
      </div>
    </div>

    <!-- 多张图片网格 -->
    <div v-else class="image-grid" :class="getGridClass()">
      <div
        v-for="(image, index) in displayImages"
        :key="image.id"
        class="image-item-wrapper"
        @click.prevent.stop="openPreview(index, $event)"
      >
        <div class="image-item">
          <img
            :src="debugFormatImageUrl(image.fileUrl)"
            :alt="image.originalName"
            :style="getImageStyle(image)"
            @load="handleImageLoad"
            @error="handleImageError"
          />
        </div>

        <!-- 更多图片遮罩 -->
        <div
          v-if="index === maxDisplay - 1 && images.length > maxDisplay"
          class="more-overlay"
        >
          <span class="more-text">+{{ images.length - maxDisplay }}</span>
        </div>
      </div>
    </div>

    <!-- 自定义图片预览 -->
    <div v-if="showPreview" class="custom-image-preview" @click="closePreview">
      <div class="preview-container" @click.stop>
        <div class="preview-header">
          <span class="preview-title"
            >{{ currentIndex + 1 }} / {{ images.length }}</span
          >
          <button class="close-btn" @click="closePreview">×</button>
        </div>
        <div class="preview-content">
          <button
            v-if="images.length > 1"
            class="nav-btn prev"
            @click="prevImage"
          >
            ‹
          </button>
          <img
            :src="debugFormatImageUrl(images[currentIndex].fileUrl)"
            :alt="images[currentIndex].originalName"
            class="preview-image"
          />
          <button
            v-if="images.length > 1"
            class="nav-btn next"
            @click="nextImage"
          >
            ›
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import type { CommentImageInfo } from "@/api/comment-image";
import { formatImageUrl } from "@/utils/avatar";

// Props定义
interface Props {
  /** 图片列表 */
  images: CommentImageInfo[];
  /** 最大显示数量 */
  maxDisplay?: number;
  /** 图片布局模式 */
  layout?: "grid" | "waterfall";
}

const props = withDefaults(defineProps<Props>(), {
  maxDisplay: 9,
  layout: "grid"
});

// 响应式数据
const showPreview = ref(false);
const currentIndex = ref(0);

// 计算属性
const displayImages = computed(() => {
  return props.images.slice(0, props.maxDisplay);
});

// 所有图片的URL列表，用于预览
const allImageUrls = computed(() => {
  return props.images.map(image => debugFormatImageUrl(image.fileUrl));
});

// 根据图片宽高比决定显示方式
const getImageStyle = (image: CommentImageInfo) => {
  if (!image.width || !image.height) {
    return { objectFit: "contain" as const };
  }

  const aspectRatio = image.width / image.height;

  // 智能选择显示方式：
  // - 正方形或横图 (宽高比 >= 0.75): 使用 cover 填满容器
  // - 竖图 (宽高比 < 0.75): 使用 contain 显示完整内容
  // 这样可以避免竖图被过度裁切，同时让横图和正方形图片填满容器
  if (aspectRatio >= 0.75) {
    return { objectFit: "cover" as const };
  } else {
    return { objectFit: "contain" as const };
  }
};

// 获取网格样式类
const getGridClass = (): string => {
  const count = Math.min(props.images.length, props.maxDisplay);

  if (count <= 3) {
    return `grid-${count}`;
  } else if (count <= 6) {
    return "grid-multi";
  } else {
    return "grid-many";
  }
};

// 打开预览
const openPreview = (index: number, event?: Event) => {
  // 完全阻止事件的默认行为和冒泡
  if (event) {
    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();
  }

  currentIndex.value = index;
  showPreview.value = true;
};

// 关闭预览
const closePreview = () => {
  showPreview.value = false;
  currentIndex.value = 0;
};

// 上一张图片
const prevImage = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
  } else {
    currentIndex.value = props.images.length - 1;
  }
};

// 下一张图片
const nextImage = () => {
  if (currentIndex.value < props.images.length - 1) {
    currentIndex.value++;
  } else {
    currentIndex.value = 0;
  }
};

// 处理图片加载
const handleImageLoad = () => {
  // 图片加载完成的处理
  console.log("🖼️ 评论图片加载完成");
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  console.error(`🖼️ 图片加载失败: ${img.src}`);
  // 设置错误占位图
  img.src =
    "";
};

// 键盘事件处理
const handleKeydown = (event: KeyboardEvent) => {
  if (!showPreview.value) return;

  switch (event.key) {
    case "Escape":
      closePreview();
      break;
    case "ArrowLeft":
      prevImage();
      break;
    case "ArrowRight":
      nextImage();
      break;
  }
};

// 生命周期钩子
onMounted(() => {
  document.addEventListener("keydown", handleKeydown);
});

onUnmounted(() => {
  document.removeEventListener("keydown", handleKeydown);
});

// 调试用的图片URL格式化
const debugFormatImageUrl = (url: string): string => {
  const formattedUrl = formatImageUrl(url);
  console.log(`🖼️ 图片URL格式化: ${url} -> ${formattedUrl}`);
  return formattedUrl;
};
</script>

<style scoped lang="scss">
// 移动端适配
@media (width <= 768px) {
  .comment-image-viewer {
    .single-image {
      .image-item {
        max-width: 120px;
        max-height: 90px;
      }
    }

    .image-grid {
      gap: 2px;
      max-width: 180px;

      &.grid-1 {
        max-width: 120px;
      }

      &.grid-2 {
        max-width: 150px;
      }

      &.grid-3,
      &.grid-multi,
      &.grid-many {
        grid-template-columns: repeat(3, 1fr);
        max-width: 180px;
      }

      .image-item-wrapper {
        width: 50px;
        height: 50px;

        .image-error {
          font-size: 10px;

          .el-icon {
            margin-bottom: 2px;
            font-size: 16px;
          }
        }
      }
    }
  }
}

// 移动端适配
@media (width <= 768px) {
  .custom-image-preview {
    .preview-container {
      max-width: 100vw;
      max-height: 100vh;
    }

    .preview-content {
      .preview-image {
        max-width: 95vw;
        max-height: 85vh;
      }

      .nav-btn {
        width: 50px;
        height: 50px;
        font-size: 36px;

        &.prev {
          left: 10px;
        }

        &.next {
          right: 10px;
        }
      }
    }
  }
}

.comment-image-viewer {
  margin: 8px 0;

  .single-image {
    .image-item {
      max-width: 180px;
      max-height: 120px;
      overflow: hidden;
      cursor: pointer;
      border-radius: 6px;
      transition: transform 0.2s ease;

      img {
        width: 100%;
        height: 100%;
        border-radius: 6px;
      }

      &:hover {
        transform: scale(1.02);
      }
    }
  }

  .image-grid {
    display: grid;
    gap: 3px;
    max-width: 300px;
    overflow: hidden;
    border-radius: 6px;

    &.grid-1 {
      grid-template-columns: 1fr;
      max-width: 180px;
    }

    &.grid-2 {
      grid-template-columns: 1fr 1fr;
      max-width: 200px;
    }

    &.grid-3 {
      grid-template-columns: repeat(3, 1fr);
      max-width: 250px;
    }

    &.grid-multi {
      grid-template-rows: repeat(2, 1fr);
      grid-template-columns: repeat(3, 1fr);
      max-width: 250px;
    }

    &.grid-many {
      grid-template-rows: repeat(3, 1fr);
      grid-template-columns: repeat(3, 1fr);
      max-width: 250px;
    }

    .image-item-wrapper {
      position: relative;
      width: 70px;
      height: 70px;
      aspect-ratio: 1;
      overflow: hidden;

      .image-item {
        width: 100%;
        height: 100%;
        overflow: hidden;
        cursor: pointer;
        border-radius: 4px;
        transition: transform 0.2s ease;

        img {
          width: 100%;
          height: 100%;
          border-radius: 4px;
        }

        &:hover {
          transform: scale(1.05);
        }
      }

      .image-error {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        font-size: 12px;
        color: #999;
        background: #f5f5f5;
        border-radius: 4px;

        .el-icon {
          margin-bottom: 4px;
          font-size: 20px;
        }
      }

      .more-overlay {
        position: absolute;
        inset: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
        font-weight: 600;
        color: white;
        background: rgb(0 0 0 / 60%);
        border-radius: 4px;

        .more-text {
          text-shadow: 0 1px 2px rgb(0 0 0 / 50%);
        }
      }
    }
  }
}

// 暗色主题适配
.dark {
  .comment-image-viewer {
    .image-grid {
      .image-item-wrapper {
        .image-error {
          color: #86909c;
          background: #2a2a3a;
        }

        .more-overlay {
          background: rgb(0 0 0 / 80%);
        }
      }
    }

    .single-image {
      .image-error {
        color: #86909c;
        background: #2a2a3a;
      }
    }
  }
}

// 自定义图片预览样式
.custom-image-preview {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: rgb(0 0 0 / 90%);

  .preview-container {
    position: relative;
    display: flex;
    flex-direction: column;
    max-width: 90vw;
    max-height: 90vh;
  }

  .preview-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    color: white;

    .preview-title {
      font-size: 16px;
      font-weight: 500;
    }

    .close-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40px;
      height: 40px;
      padding: 0;
      font-size: 32px;
      color: white;
      cursor: pointer;
      background: none;
      border: none;
      border-radius: 50%;
      transition: background-color 0.2s;

      &:hover {
        background-color: rgb(255 255 255 / 10%);
      }
    }
  }

  .preview-content {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    .preview-image {
      max-width: 80vw;
      max-height: 80vh;
      object-fit: contain;
      border-radius: 8px;
    }

    .nav-btn {
      position: absolute;
      top: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 60px;
      font-size: 48px;
      color: white;
      cursor: pointer;
      background: rgb(255 255 255 / 20%);
      border: none;
      border-radius: 50%;
      transform: translateY(-50%);
      transition: background-color 0.2s;

      &:hover {
        background: rgb(255 255 255 / 30%);
      }

      &.prev {
        left: -80px;
      }

      &.next {
        right: -80px;
      }
    }
  }
}
</style>
